import pythoncom
import PyHook3
import time

from Moniter.MoniterController import MonController


class ListenWorker():

    def __init__(self):
        #设置工作状态与初始num数值
        self.working = False
        self.num = 0
        self.mc = MonController()
        print('**Listen** before hook mouse event')
        self.run()

    def mystart(self):
        print('**Listen** coming into check')
        if self.mc.check():
            self.working = True
            return True
        else:
            return False

    def mystop(self):
        self.working = False

    def init_mouse_value(self):
        # global last_time, last_x, last_y
        self.last_time = 0
        self.last_x, self.last_y = 0, 0

    def onMouse_leftdown(self, event):
        print('**LisWorker** down mouse')
        if not self.working:
            return True
        now_time = time.time()
        now_x, now_y = event.Position
        if now_time - self.last_time < 0.6 and abs(now_x - self.last_x) < 5 and abs(now_y - now_y) < 5:
            info = ' '.join(('老铁双击！', 'X: {} Y: {}'.format(*event.Position), 'time:', str(event.Time)))
            print(info)
            self.check_title()
            self.init_mouse_value()
        self.last_time = now_time
        self.last_x, self.last_y = now_x, now_y
        return True
        # 返回 True 表示响应此事件，False表示拦截

    def run(self):
        self.init_mouse_value()
        hm = PyHook3.HookManager()
        hm.MouseLeftDown = self.onMouse_leftdown
        hm.HookMouse()
        # 进入循环，如不手动关闭，程序将一直处于监听状态
        print('**LisWoker** has hook mouse event')
        pythoncom.PumpMessages()

    #
    # def run(self):
    #     print('**ListenWorker** has start')
    #     while True:
    #         if self.working:
    #             try:
    #                 stock_info = self.rece_queue.get(block=False)
    #                 stock_info = stock_info.decode()
    #                 print('**ListenWorker** has get stock', stock_info)
    #                 self.sinOut.emit(stock_info)
    #             except Empty:
    #                 pass
    #         else:
    #             pass